<template>
  <div class="container">
    <div class="add">
      <el-button type="primary" @click="addCategory">增加分类</el-button>
    </div>
    <el-divider></el-divider>
    <el-table
        :data="tableData"
        stripe
        style="width: 100%">
      <el-table-column
          prop="name"
          label="分类名称"
          align="center"
      >
      </el-table-column>
      <el-table-column
          prop="isShow"
          label="是否展示"
          align="center"
      >
      </el-table-column>
      <el-table-column
          label="操作"
          align="center"
      >
        <template slot-scope="scope">
          <el-button size="small" type="primary" @click="editCategory(scope)">修改</el-button>
          <el-button size="small" type="danger" @click="delCategory(scope.row._id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        @current-change="handleCurrentChange"
        :current-page.sync="currentPage"
        :page-size="pageSize"
        layout="prev, pager, next, jumper"
        :total="total">
    </el-pagination>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //表格数据
      tableData: [],
      //分页变量
      currentPage:1,
      pageSize:10,
      total:0
    }
  },
  created() {
    this.getCategory()
  },
  methods:{
    //删除分类
    delCategory(_id){
      this.$confirm(`您确定删除吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 确定操作
        const result=await this.$http.delete(`category/del/${_id}`)
        if(result.data.status=="success"){
          this.$message.success("删除成功")
          this.getCategory()
        }else {
          this.$message.success("删除失败,请稍后重试...")
        }
      }).catch(() => {
        // 取消操作
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    //修改分类
    editCategory(scope){
      this.$router.push({
        name:'categoryEdit',
        query:{
          action:'edit',
          info:JSON.stringify(scope.row)//只能传递字符串
        }
      })
    },
    //添加分类
    addCategory(){
      this.$router.push({
        name:'categoryEdit',
        query:{
          action:'add'
        }
      })
    },
    //数据查询
    getCategory(){
      const param={params:{currentPage:this.currentPage,pageSize:this.pageSize}}
      this.$http.get('category/getCategory',param).then((res)=>{
        if(res.data.status=='success'){
           this.total=res.data.total
           this.tableData=res.data.data
        }
      }).catch((err)=>{
        this.$message.error("网络错误...")
      })
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.currentPage=val
      //刷新新页
      this.getCategory()
    }
  }
}
</script>

<style lang="scss" scoped>
.container{
  background-color: #fff;
  padding: 10px;
  .add{
    display: flex;
    justify-content: right;
  }
}
</style>